// import { baseUrlForWebSocket } from "../utils/Request";


// let baseUrlForWebSocket = 'ws://localhost:8080/'
let baseUrlForWebSocket = '/'

const ports = []
const uuids = []

let token = null

let webSocket = null;

// sharedworker 连接时的回调函数
self.onconnect = (e) => {
    // 获取页面端口
    const port = e.ports[0];
    // 获取页面标识
    const uuid = Math.random().toString(36).substr(2);

    ports.push(port)
    uuids.push(uuid)

    // 发送回主线程
    port.postMessage({
        type: 'connected',
        uuid: uuid,
    });

    // 监听主线程的消息
    port.onmessage = (e) => {
        if (e.data.type == 'connected') {
            if (webSocket == null || webSocket.readyState == WebSocket.CLOSED) {
                token = e.data.data
                baseUrlForWebSocket = e.data.url
                webSocketServer()
            }
        } else if (e.data.type === 'close') {

            let index = uuids.indexOf(e.data.uuid)
            ports.splice(index, 1)
            uuids.splice(index, 1)

            if (ports.size == 0) {
                if (webSocket != null) {
                    webSocket.close()
                }
                self.close()
            }
        } else if (e.data.type === 'closeWebSocket') {
            if (webSocket != null) {
                webSocket.close()
                console.log('关闭WebSocket')
            }
        }
    };

};



/*
    WebSocket 通信
*/
const webSocketServer = () => {

    webSocket = new WebSocket(`${baseUrlForWebSocket}api/message/websocket?Authorization=${token}`)

    let heartTimer = null

    // 连接成功后的回调函数
    webSocket.onopen = function (e) {
        console.log('WebSocket连接成功')
        broadcastMessage('log', 'WebSocket连接成功')

        // 定时发送心跳包
        heartTimer = setInterval(() => {
            webSocket.send('ping')
        }, 30000)
        

    };

    // 从服务器接受到信息时的回调函数
    webSocket.onmessage = function (e) {
        console.log('收到服务器响应', e.data)
        let msgType = 'msg'
        if (e.data == 'pong') {
            msgType = 'log'
        }
        broadcastMessage(msgType, e.data)
    };

    // 连接关闭后的回调函数
    webSocket.onclose = function (e) {
        console.log("关闭WebSocket连接")
        broadcastMessage('log', 'WebSocket连接关闭')
        if (heartTimer) {
            clearInterval(heartTimer)
        }
    };

    // 连接失败后的回调函数
    webSocket.onerror = function (e) {
        console.log("WebSocket连接失败了")
        broadcastMessage('log', 'WebSocket连接失败了')
        broadcastMessage('log', JSON.stringify(e))
    };
}

const broadcastMessage = (type, msg) => {
    ports.forEach((port) => {
        port.postMessage({
            type: type,
            data: msg
        })
    })
}


